import 'dart:math';

import 'package:hi_common/hi_common.dart';
import 'package:flutter/material.dart';

class Badge extends StatefulWidget {
  final Widget child;
  final int count;
  final int max;
  final bool isJustShowDot;

  const Badge({
    Key key,
    this.child,
    this.count,
    this.max,
    this.isJustShowDot = false,
  }) : super(key: key);

  @override
  _BadgeState createState() => _BadgeState();
}

class _BadgeState extends State<Badge> {
  String get countText => min(widget.max ?? widget.count, widget.count).toString();

  @override
  Widget build(BuildContext context) {
    double size = widget.isJustShowDot ? 8 : 16;
    double padding = widget.isJustShowDot ? 0 : 5;

    return Container(
      child: Stack(
        overflow: Overflow.visible,
        children: <Widget>[
          widget.child,
          if (widget.count > 0)
            Positioned(
              top: ScreenUtil.instance.setWidth(-8),
              right: -size / 2,
              child: Container(
                padding: EdgeInsets.symmetric(
                  horizontal: padding,
                ),
                constraints: BoxConstraints(
                  minWidth: size,
                  minHeight: size,
                ),
                decoration: BoxDecoration(
                  color: Colors.red,
                  borderRadius: BorderRadius.circular(size),
                ),
                alignment: Alignment.center,
                child: widget.isJustShowDot
                    ? null
                    : Text(
                        '$countText',
                        softWrap: false,
                        style: TextStyle(
                          fontSize: 10,
                          color: Colors.white,
                        ),
                      ),
              ),
            )
        ],
      ),
    );
  }
}
